import { Controller, Post, UseInterceptors, UploadedFile, BadRequestException } from '@nestjs/common';
import { ImageUploadInterceptor } from '../../common/interceptors/image-upload.interceptor';
import { UploadService } from './upload.service';
import { Public } from '../../common/decorators/public.decorator';
import { ApiTags, ApiOperation, ApiResponse, ApiConsumes, ApiBody } from '@nestjs/swagger';

@ApiTags('文件上传')
@Controller('api/upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {}

  @Post('image')
  @UseInterceptors(ImageUploadInterceptor('file', {
    maxSize: 5 * 1024 * 1024, // 5MB 大小限制
    allowedMimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  }))
  @ApiOperation({
    summary: '上传图片',
    description: '上传图片文件到服务器',
  })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @ApiResponse({
    status: 200,
    description: '上传成功',
    schema: {
      example: {
        url: 'https://example.com/uploads/image.jpg',
        filename: 'image.jpg',
      },
    },
  })
  @ApiResponse({
    status: 400,
    description: '没有文件被上传或文件类型错误',
  })
  async uploadImage(@UploadedFile() file: any) {
    if (!file) {
      throw new BadRequestException('没有文件被上传');
    }
    
    // 二次检查文件大小，确保符合限制
    if (file.size > 5 * 1024 * 1024) {
      throw new BadRequestException('文件大小超过限制，最大允许5MB');
    }
    
    return this.uploadService.uploadFile(file);
  }
}